package eai.tp2.core;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import eai.tp2.core.datamodel.CameraSummary;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * This class receives the list of brand summaries and generate the output xml file.
 * 
 * @author Simão
 */
public class CameraSummaryWriter {

    private Document doc;
    List<CameraSummary> cameras;

    public CameraSummaryWriter(List<CameraSummary> cameras) {

        this.cameras = cameras;
    }

    public void write() {
        CameraSummary camera;

        for (int i = 0; i < cameras.size(); i++) {
            doc = new Document();
            Element root = new Element("manufacture_list");
            Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            root.setAttribute("noNamespaceSchemaLocation", "CameraSummary.xsd", xsi);

            camera = cameras.get(i);

            Element cameraElement = new Element("manufacture");
            cameraElement.setAttribute("name", camera.getManufacturer());
            cameraElement.setAttribute("num_cams", "" + camera.getNumCameras());

            addAtributes(cameraElement, SummaryEngine.MOST_RECENT, "date" ,camera.getMostRecentCamera().getDate(), "model", camera.getMostRecentCamera().getModel());
            addAtributes(cameraElement, SummaryEngine.OLDEST, "date" ,camera.getOldestCamera().getDate(), "model", camera.getOldestCamera().getModel());
            addAtributes(cameraElement, SummaryEngine.MAX_RES, "value" ,camera.getMaxResolution().getResolution(), "model", camera.getMaxResolution().getModel());
            addAtributes(cameraElement, SummaryEngine.MIN_RES, "value" ,camera.getMinResolution().getResolution(), "model", camera.getMinResolution().getModel());

            List<String> models = camera.getManufacturerModels();
            Element modelsElement = new Element("model_list");
            for (int j = 0; j < models.size(); j++) {

                addElement(modelsElement, models.get(j), "model", "");

            }

            cameraElement.addContent(modelsElement);

            root.addContent(cameraElement);
            doc.setRootElement(root);
            createXML(camera.getManufacturer() + "_Summary.xml");

            System.out.println(camera.getManufacturer() + "_Summary.xml file just writed!");

            validateXML(camera.getManufacturer() + "_Summary.xml");
        }

    }
    
    public Document write(CameraSummary summary) {
    	 Document doc = new Document();
         Element root = new Element("manufacture_list");
         Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
         root.setAttribute("noNamespaceSchemaLocation", "CameraSummary.xsd", xsi);
         Element cameraElement = new Element("manufacture");
         cameraElement.setAttribute("name", summary.getManufacturer());
         cameraElement.setAttribute("num_cams", "" + summary.getNumCameras());

         addAtributes(cameraElement, SummaryEngine.MOST_RECENT, "date" ,summary.getMostRecentCamera().getDate(), "model", summary.getMostRecentCamera().getModel());
         addAtributes(cameraElement, SummaryEngine.OLDEST, "date" ,summary.getOldestCamera().getDate(), "model", summary.getOldestCamera().getModel());
         addAtributes(cameraElement, SummaryEngine.MAX_RES, "value" ,summary.getMaxResolution().getResolution(), "model", summary.getMaxResolution().getModel());
         addAtributes(cameraElement, SummaryEngine.MIN_RES, "value" ,summary.getMinResolution().getResolution(), "model", summary.getMinResolution().getModel());

         List<String> models = summary.getManufacturerModels();
         Element modelsElement = new Element("model_list");
         for (int j = 0; j < models.size(); j++) {
             addElement(modelsElement, models.get(j), "model", "");
         }
         cameraElement.addContent(modelsElement);
         root.addContent(cameraElement);
         doc.setRootElement(root);
         return doc;
    }
    
    private void addElement(Element el, String content, String tag, String attribute) {

        Element temp = new Element(tag);
        if (!attribute.equals("")) {
            temp.setAttribute("model", attribute);
        }
        temp.addContent(content);
        el.addContent(temp);
    }

    public void createXML(String fileName) {

        try {
            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            FileWriter writer = new FileWriter(System.getProperty("user.dir") + "\\data\\" + fileName);
            outputter.output(doc, writer);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean validateXML(String filename) {


        try {
            SAXBuilder builder = new SAXBuilder(true);
            builder.setFeature("http://apache.org/xml/features/validation/schema", true);
            Document doc = builder.build("data/" + filename);

            System.out.println(filename + " file validated correctly!");

        } catch (JDOMException ex) {
            Logger.getLogger(CameraSummaryWriter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CameraSummaryWriter.class.getName()).log(Level.SEVERE, null, ex);
        }

        return true;
    }

    private void addAtributes(Element el, String elementName,  String tag1, String date, String tag2, String model) {

        Element temp = new Element(elementName);
        
        if (!tag2.equals("")) {
            temp.setAttribute(tag2, model);
        }

        if (!tag1.equals("")) {
            temp.setAttribute(tag1, date);
        }
        
        el.addContent(temp);
    }
}
